const db = require("../models");
const utils = require('../utils');
const Role = db.models.roles;
const Menu = db.models.menus;
/**
 * 组装菜单树
 */
function assembleRouter(list) {
    let menuMap = {}, routes = [];
    list.sort((a, b) => a.rank - b.rank);
    list.forEach(menu => {
        menuMap[menu.id] = {
            path: menu.path ?? '',
            name: menu.name ?? '',
            menu_type: menu.menu_type ?? '',
            parent_id: menu.parent_id,
            redirect: menu.redirect ?? '',
            component: menu.component ?? '',
            meta: {
                title: menu.title ?? '',
                icon: menu.icon ?? '',
                rank: menu.rank ?? 99,
                extra_icon: menu.extra_icon ?? '',
                active_path: menu.active_path??'',
                // auths: menu.auths ? [menu.auths] : [],
                frame_src: menu.frame_src ?? null,
                frame_loading: menu.frame_loading ?? true,
                show_link: menu.show_link ?? true,
                show_parent: menu.show_parent ?? false,
                keep_alive: menu.keep_alive ?? false,
                hidden_tag: menu.hidden_tag ?? false,
                fixed_tag: menu.fixed_tag ?? false,
                transition: {
                    // name: menu.enterTransition ?? null,
                    enter_transition: menu.enter_transition ?? null,
                    leave_transition: menu.leave_transition ?? null,
                },
            },
        }
    });
    list.forEach(item => {
        let parent = menuMap[item.parent_id];
        if (parent) {
            if(item.menu_type === 3){
                parent.meta.auths??=[];
                parent.meta.auths.push(item.auths);
            }else{
                parent.children ??= [];
                parent.children.push(menuMap[item.id]);
            }
        } else {
            routes.push(menuMap[item.id]);
        }
    });
    return  utils.tools.cleanObject(routes)
}
/**
 * 从角色中获取路由并去重
 */
function getRouter(roles) {
    let allMenu = [];
    roles.forEach(r => allMenu = allMenu.concat(r.pure_menus));
    const uniqueMenu = allMenu.reduce((pre, cur) => {
        const x = pre.find(item => item.id === cur.id);
        if (!x) {
            return pre.concat(cur);
        } else {
            return pre;
        }
    }, []);
    return assembleRouter(uniqueMenu);
}
exports.getRoutes = (req, res) => {
    if (!req.user.role_ids || !req.user.role_ids.length) return res.sendResultAto(null, 4, "请登录");
    Role.findAll({
        where: { id: req.user.role_ids },
        include: [{ model: Menu, attributes: { exclude: [] }, through: { attributes: [] } }]
    }).then(list => {
        const router = getRouter(JSON.parse(JSON.stringify(list)));
        // 将路由保存到session中，供权限判断使用
        req.session.userRouter = router;
        res.sendResultAto(router, 0, '操作成功！');
    })
}